﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using ZXing;
using ZXing.QrCode;

namespace PewPew.Logic
{
    public static class QrProcessor
    {

        private static readonly Func<Bitmap, LuminanceSource> defaultCreateLuminanceSource =
           (bitmap) => new BitmapLuminanceSource(bitmap);

        private static BarcodeReader reader = new BarcodeReader(new QRCodeReader(), defaultCreateLuminanceSource, null)  { AutoRotate = true, TryHarder = true };

        /// <summary>
        /// Returns the content of a QR code within a given Kinect frame.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        /// <returns>The message decoded or null</returns>
        public static Result ProcessQRInKinectImage(WriteableBitmap bitmap)
        {
            // jump through some hoops to make Zxing happy
            var imgPrgbra32 = BitmapFactory.ConvertToPbgra32Format(bitmap);
            // flip it because Kinect provides a mirror image
            var imgFlipped = WriteableBitmapExtensions.Flip(imgPrgbra32, WriteableBitmapExtensions.FlipMode.Horizontal);
            // i heard you like function compositioning
            var rgb = WriteableBitmapExtensions.ToByteArray(imgFlipped);
            // now we can process
            return ProcessQRInImage(rgb, imgFlipped.PixelHeight, imgFlipped.PixelWidth);
        }

        /// <summary>
        /// Returns the content of a QR code within a given bitmap.
        /// </summary>
        /// <param name="bitmap">The bitmap.</param>
        /// <returns>The message decoded or null</returns>
        public static Result ProcessQRInImage(byte[] b, int height, int width)
        {
            try
            {
                var res = reader.Decode(b, width, height, RGBLuminanceSource.BitmapFormat.RGB32);
                return res;
            }
            catch
            {
                return null;
            }
         }

    }
}
